import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:refreshlistdemo/list_data_item.dart';

class RefreshListPage extends StatefulWidget {
  const RefreshListPage({super.key});

  @override
  State<RefreshListPage> createState() => _RefreshListPageState();
}

class _RefreshListPageState extends State<RefreshListPage> {
  // 定义原始数据
  List<String> items = [
    "1",
    "2",
  ];

  // 定义刷新控制器
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  void _onRefresh() async {
    // 模拟网络请求,此处延时1秒
    await Future.delayed(Duration(milliseconds: 1000));

    // 刷新成功，数据恢复原样
    // 刷新成功，数据恢复原样
    items = [
      "1",
      "2",
      "3",
      "4",
      "3",
      "4",
      "3",
      "4",
    ];
    if (mounted) {
      setState(() {});
    }
    // 重置获取数据LoadStatus
    _refreshController.refreshCompleted(resetFooterState: true);
  }

  void _onLoading() async {
    // 模拟网络请求,此处延时1秒
    await Future.delayed(const Duration(milliseconds: 1000));
    // 每次模拟加载数据，等到数据加载到20个为止，模拟数据都获取完成, 并设置LoadStatus
    if (items.length >= 2) {
      _refreshController.loadNoData();
      return;
    }
    //每次加载两个数据
    items.add((items.length + 1).toString());
    if (mounted) {
      setState(() {});
    }
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            "列表刷新",
            style: TextStyle(color: Colors.black38, fontSize: 18),
          ),
        ),
        body: RefreshConfiguration(
          footerTriggerDistance: 80,
          //   dragSpeedRatio: 0.91,
          hideFooterWhenNotFull: true,
          headerBuilder: () => const ClassicHeader(),
          footerBuilder: () => const ClassicFooter(),
          child: SmartRefresher(
            dragStartBehavior: DragStartBehavior.down,
            enablePullDown: true, // 下拉刷新
            enablePullUp: true, // 上拉加载数据
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              itemBuilder: (c, i) => Card(
                  child: Center(
                      child: Text(
                items[i],
                style: const TextStyle(fontSize: 10.0),
              ))),
              itemExtent: 100.0,
              itemCount: items.length,
            ),
          ),
        ));
  }
}
